<?php

namespace App\Controller\websocket;

use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\WebSocketServer\Constant\Opcode;
use hg\apidoc\annotation as Apidoc;
use Swoole\Timer;
use Swoole\WebSocket\Frame;

#[AutoController]
#[Apidoc\Title('WebSocket')]
#[Apidoc\Group('websocket')]
class WebSocketController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{
    public function onMessage($server, $frame): void
    {
        if($frame->opcode == Opcode::PING) {
            // 如果使用协程 Server，在判断是 PING 帧后，需要手动处理，返回 PONG 帧。
            // 异步风格 Server，可以直接通过 Swoole 配置处理，详情请见 https://wiki.swoole.com/#/websocket_server?id=open_websocket_ping_frame
            $server->push('', Opcode::PONG);
            return;
        }
        $server->push($frame->fd, 'Recv: ' . $frame->data);
    }

    public function onClose($server, int $fd, int $reactorId): void
    {
        var_dump('closed');
    }

    public function onOpen($server, $request): void
    {
        Timer::tick(35000, function () use ($server, $request){
            // 发送 PING
            $pingFrame = new Frame;
            $pingFrame->opcode = WEBSOCKET_OPCODE_PING;
            $server->push($request->fd, $pingFrame);
            return true;
        });
        //$server->push($request->fd, 'Opened');
    }
}